package com.android.webttest.ViewModel;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.android.webttest.Api.Service.AppApiService;
import com.android.webttest.Api.Service.CategoryApiService;
import com.android.webttest.Api.Service.GoodApiService;
import com.android.webttest.Config.ApiClient;
import com.android.webttest.model.Category;
import com.android.webttest.model.Good;
import com.android.webttest.model.GoodAllInfo;
import com.android.webttest.model.GoodDetailInfo;
import com.android.webttest.model.HeatData;
import com.android.webttest.model.PageBean;
import com.android.webttest.model.Result;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GoodViewModel extends AndroidViewModel {

    //category
    private MutableLiveData<List<Category>> categoryListLiveData;
    private CategoryApiService  categoryApiService;
    //good
    private MutableLiveData<List<Good>> goodListLiveData;
    private MutableLiveData<List<GoodDetailInfo>> goodDetailInfoListLiveData;
    private MutableLiveData<List<HeatData>> heatDataListLiveData;

    private MutableLiveData<GoodAllInfo> goodAllInfoLiveData;

    private GoodApiService goodApiService;

    private AppApiService  appApiService;

    public GoodViewModel(@NonNull Application application) {
        super(application);
        categoryListLiveData = new MutableLiveData<>();
        categoryApiService = ApiClient.getCategoryApiServiceClient(application.getApplicationContext());
        goodListLiveData = new MutableLiveData<>();
        goodListLiveData.setValue(new ArrayList<>()); // 初始化为空列表
        goodDetailInfoListLiveData = new MutableLiveData<>();
        heatDataListLiveData = new MutableLiveData<>();
        goodAllInfoLiveData = new MutableLiveData<>();
        goodApiService = ApiClient.getGoodApiServiceClient(application.getApplicationContext());
        appApiService = ApiClient.getAppApiServiceClient(application.getApplicationContext());
    }

    public LiveData<List<Category>> getCategoryListLiveData() {
        return categoryListLiveData;
    }

    public LiveData<List<Good>> getGoodListLiveData() {
        return goodListLiveData;
    }

    public LiveData<List<GoodDetailInfo>> getGoodDetailInfoListLiveData() {
        return goodDetailInfoListLiveData;
    }

    public LiveData<List<HeatData>> getHeatDataListLiveData() {
        return heatDataListLiveData;
    }


    public LiveData<GoodAllInfo> getGoodAllInfoLiveData() { return goodAllInfoLiveData;}
    public void getGoodCategoryList() {
        categoryApiService.list().enqueue(new Callback<Result<List<Category>>>() {
            // 获取成功--call: 表示当前的网络请求。--response: 表示服务器的响应。
            @Override
            public void onResponse(Call<Result<List<Category>>> call, Response<Result<List<Category>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<Category> categoryList = response.body().getData();
                    // 创建一个新的 Category 对象
                    Category all = new Category();
                    all.setCategoryName("全部");
                    all.setCategoryAlias("all");
                    all.setId(null);
                    // 在 categoryList 的第一个位置添加新元素
                    categoryList.add(0, all);
                    // 设置 categoryListLiveData
                    categoryListLiveData.setValue(categoryList);
                    Log.d("GoodViewModel", "Successfully got category list: " + response.body().getData());
                } else {
                    // 处理错误
                    categoryListLiveData.setValue(null);
                    //打印错误信息
                    Log.d("GoodViewModel", "Failed to get category list: " + response.code());
                }
            }
            // 获取失败--call: 表示当前的网络请求。--t: 表示错误信息。
            @Override
            public void onFailure(Call<Result<List<Category>>> call, Throwable t) {
                // 处理失败
                categoryListLiveData.setValue(null);
                //打印错误信息
                Log.d("GoodViewModel", "Failed to get category list: " + t.getMessage());
            }
        });
    }
    //good
    public void getGoodList(Integer pageNum, Integer pageSize, Integer categoryId, String state, Double minPrice, Double maxPrice, String keyWords) {
        if (pageNum == null || pageSize == null) {
            Log.e("GoodViewModel", "pageNum and pageSize are required");
            return;
        }

        fetchGoodListRecursive(pageNum, pageSize, categoryId, state, minPrice, maxPrice, keyWords);
    }

    private void fetchGoodListRecursive(Integer pageNum, Integer pageSize, Integer categoryId, String state, Double minPrice, Double maxPrice, String keyWords) {
        goodApiService.list(
                pageNum,
                pageSize,
                categoryId,
                state,
                minPrice,
                maxPrice,
                keyWords
        ).enqueue(new Callback<Result<PageBean<Good>>>() {
            @Override
            public void onResponse(Call<Result<PageBean<Good>>> call, Response<Result<PageBean<Good>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    PageBean<Good> goodPageBean = response.body().getData();
                    if (goodPageBean != null && goodPageBean.getItems() != null && !goodPageBean.getItems().isEmpty()) {
                        // 添加到 List
                        List<Good> currentList = goodListLiveData.getValue();
                        if (currentList == null) {
                            currentList = new ArrayList<>();
                        }
                        currentList.addAll(goodPageBean.getItems());
                        goodListLiveData.setValue(currentList);

                        // 请求下一页
                        fetchGoodListRecursive(pageNum + 1, pageSize, categoryId, state, minPrice, maxPrice, keyWords);
                    } else {
                        // 结束请求
                        Log.d("GoodViewModel", "No more data to fetch");
                        getGoodRelation();
                    }
                } else {
                    goodListLiveData.setValue(null);
                    Log.d("GoodViewModel", "Failed to get good list: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Result<PageBean<Good>>> call, Throwable t) {
                goodListLiveData.setValue(null);
                Log.d("GoodViewModel", "Failed to get good list: " + t.getMessage());
            }
        });
    }
    //goodDetailInfo
    public void getGoodDetailInfo(Integer goodId) {

        if (goodId == null) {
            Log.e("GoodViewModel", "getGoodDetailInfo goodId is required");
            return;
        }
        goodApiService.getGoodDetailInfo(goodId).enqueue(new Callback<Result<GoodDetailInfo>>() {

            @Override
            public void onResponse(Call<Result<GoodDetailInfo>> call, Response<Result<GoodDetailInfo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    GoodDetailInfo goodDetailInfo = response.body().getData();
                    if (goodDetailInfo != null) {
                        // 获取当前的 goodDetailInfoListLiveData 值
                        List<GoodDetailInfo> currentList = goodDetailInfoListLiveData.getValue();
                        if (currentList == null) {
                            currentList = new ArrayList<>();
                        }
                        // 添加新的 GoodDetailInfo 到列表中
                        currentList.add(goodDetailInfo);
                        goodDetailInfoListLiveData.setValue(currentList);
                        Log.d("GoodViewModel", "Successfully got good detail info: " + goodDetailInfo);
                    } else {
                        Log.d("GoodViewModel", "Good detail info is null");
                    }
                } else {
                    goodDetailInfoListLiveData.setValue(null);
                    Log.d("GoodViewModel", "Failed to get good detail info: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Result<GoodDetailInfo>> call, Throwable t) {
                goodDetailInfoListLiveData.setValue(null);
                Log.d("GoodViewModel", "Failed to get good detail info: " + t.getMessage());
            }
        });
    }

    //heatData
    public void getGoodHeatData(Integer goodId) {
        if (goodId == null) {
            Log.e("GoodViewModel", "getGoodHeatData goodId is required");
            return;
        }

        goodApiService.getGoodHeatData(goodId).enqueue(new Callback<Result<HeatData>>() {
            @Override
            public void onResponse(Call<Result<HeatData>> call, Response<Result<HeatData>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    HeatData heatData = response.body().getData();
                    if (heatData != null) {
                        // 获取当前的 heatDataListLiveData 值
                        List<HeatData> currentList = heatDataListLiveData.getValue();
                        if (currentList == null) {
                            currentList = new ArrayList<>();
                        }
                        // 添加新的 HeatData 到列表中
                        currentList.add(heatData);
                        heatDataListLiveData.setValue(currentList);
                        Log.d("GoodViewModel", "Successfully got good heat data: " + heatData);
                    } else {
                        Log.d("GoodViewModel", "Heat data is null");
                    }
                } else {
                    heatDataListLiveData.setValue(null);
                    Log.d("GoodViewModel", "Failed to get good heat data: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Result<HeatData>> call, Throwable t) {
                heatDataListLiveData.setValue(null);
                Log.d("GoodViewModel", "Failed to get good heat data: " + t.getMessage());
            }
        });
    }

    public void getGoodRelation(){
        List<Good> goodList = goodListLiveData.getValue();
        if (goodList != null && !goodList.isEmpty()) {
            for (Good good : goodList) {
                getGoodDetailInfo(good.getId());
                getGoodHeatData(good.getId());
            }
        }
    }

    //拿所有信息
    public void fetchGoodAllInfo(Integer goodId) {
        if (goodId == null) {
            Log.e("GoodViewModel", "fetchGoodAllInfo: goodId is null");
            return;
        }

        appApiService.fetchGoodAllInfo(goodId).enqueue(new Callback<Result<GoodAllInfo>>() {
            @Override
            public void onResponse(Call<Result<GoodAllInfo>> call, Response<Result<GoodAllInfo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    GoodAllInfo goodAllInfo = response.body().getData();
                    // 处理获取到的商品信息
                    if (goodAllInfo != null){
                        goodAllInfoLiveData.setValue(goodAllInfo);
                    }

                    Log.d("GoodViewModel", "Successfully got good all info: " + goodAllInfo);
                    Log.d("GoodViewModel", "Successfully got good all info2: " + goodId);
                    Log.d("GoodViewModel", "Successfully got good all info3: " + response.body());

                } else {
                    Log.e("GoodViewModel", "Failed to get good all info: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Result<GoodAllInfo>> call, Throwable t) {
                Log.e("GoodViewModel", "Failed to fetch good all info: " + t.getMessage());
            }
        });
    }

//    public GoodAllInfo getGoodAllInfo(Integer goodId){
//        GoodAllInfo goodAllInfo = goodAllInfoLiveData.getValue();
//        return goodAllInfo;
//    }
}
